<template>
    <div class="pcf-content">
        <!-- 搜索栏 -->
        <div class="search-content content">
            <el-form label-width="auto">
                <el-form-item label="交易市场:">
                    <el-select name="marketCode" size="mini" clearable v-model="etfQueryForm.marketCode" multiple collapse-tags>
                        <el-option
                            v-for="i in marketSelectData"
                            :key="i.dictKey"
                            :label="i.dictKeyName"
                            :value="i.dictKey"
                            :name="'marketCode' + i.dictKey"
                        ></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="二级市场代码:">
                    <el-select name="etfCode" size="mini" clearable v-model="etfQueryForm.stockCode" collapse-tags>
                        <el-option
                            v-for="i in stockCodeSelectData"
                            :key="i.stockCode"
                            :label="i.stockCode + ' ' + i.stockName"
                            :value="i.stockCode"
                            :name="'etfCode' + i.stockCode"
                        ></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="ETF类型:">
                    <el-select name="etfType" size="mini" clearable v-model="etfQueryForm.etfType" multiple collapse-tags>
                        <el-option
                            v-for="i in ETFTypeSelectData"
                            :key="i.dictKey"
                            :label="i.dictKeyName"
                            :value="i.dictKey"
                            :name="'etfType' + i.dictKey"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="ETF市场类型:">
                    <el-select name="type" size="mini" clearable v-model="etfQueryForm.type" multiple collapse-tags>
                        <el-option
                            v-for="i in ETFMarketTypeSelectData"
                            :key="i.dictKey"
                            :label="i.dictKeyName"
                            :value="i.dictKey"
                            :name="'type' + i.dictKey"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="接口类型:">
                    <el-select name="importType" size="mini" clearable v-model="etfQueryForm.importType" multiple collapse-tags>
                        <el-option
                            v-for="i in importTypeSelectData"
                            :key="i.dictKey"
                            :label="i.dictKeyName"
                            :value="i.dictKey"
                            :name="'importType' + i.dictKey"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <div class="operate">
                    <el-button name="search" type="primary" size="mini" @click="queryETFList">查询</el-button>
                    <el-button name="refresh" type="primary" size="mini" @click="queryETFList">刷新</el-button>
                    <el-button name="layout" type="primary" size="mini" @click="layoutDialog = true">布局设置</el-button>
                </div>
            </el-form>
        </div>
        <!-- ETF信息列表 -->
        <div class="pcf-table-content content">
            <RiskTablePlus
                ref="ETFTable"
                :tableData="ETFTableData"
                :column="showFieldList"
                :tableConfig="ETFTableConfig"
                :searchParams="etfQueryForm"
                @page-change="queryData"
                @cell-click="handleETFRowClick"
                v-loading="ETFtableLoading"
                :paging="etfQueryForm.paging"
                :key="tableKey"
            >
            </RiskTablePlus>
        </div>
        <!-- 成分股信息表格 -->
        <div class="stock-table-content content">
            <RiskTablePlus
                ref="xTable"
                :tableData="stockTableData"
                :tableConfig="stockTableConfig"
                :column="stockTableColumns"
                :searchParams="etfStockQueryForm"
                @page-change="queryStockData"
                v-loading="stockTableLoading"
                :paging="etfStockQueryForm.paging"
            >
            </RiskTablePlus>
        </div>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            :table-name="tableName"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import RiskTablePlus from '@/common/components/risk-table-plus.vue';
import { TableConfigVO } from '@/common/vo';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { getEtfBasicInfoList, getEtfList, getEtfStockListInfo } from '../api/etf';
import ColumnUtil from '../utils/column-util';
import ETFColumnUtil from '../utils/etf-column-util';

@Component({
    name: 'PcfInfo',
    components: {
        RiskTablePlus,
        RiskTableLayout,
    },
})
/**
 * PCF基础数据tab
 */
export default class PcfInfo extends Vue {
    @Prop()
    renderCount: number;
    ColumnUtil = new ColumnUtil();
    ETFColumnUtil = new ETFColumnUtil();

    marketSelectData: any[] = [
        { dictKey: '1', dictKeyName: '深交所' },
        { dictKey: '2', dictKeyName: '上交所' },
    ];
    stockCodeSelectData: any[] = []; // 二级市场代码下拉
    ETFTypeSelectData: any[] = [
        { dictKey: '1', dictKeyName: '股票ETF' },
        { dictKey: '2', dictKeyName: '债券ETF' },
        { dictKey: '3', dictKeyName: '交易型货币基金' },
        { dictKey: '4', dictKeyName: '黄金ETF' },
        { dictKey: '5', dictKeyName: '货币市场基金' },
        { dictKey: '6', dictKeyName: '沪港通ETF' },
        { dictKey: '7', dictKeyName: '商品期货ETF' },
    ];
    ETFMarketTypeSelectData: any[] = [
        { dictKey: '1', dictKeyName: '本市场ETF' },
        { dictKey: '2', dictKeyName: '跨境ETF' },
        { dictKey: '3', dictKeyName: '跨市场ETF(交易所)' },
        { dictKey: '4', dictKeyName: '跨市场ETF(中登)' },
        { dictKey: '5', dictKeyName: '沪港通ETF' },
        { dictKey: '6', dictKeyName: '深港通ETF' },
    ];
    importTypeSelectData: any[] = [
        { dictKey: '1', dictKeyName: '公告1.0接口' },
        { dictKey: '2', dictKeyName: '交易2.0接口' },
        { dictKey: '3', dictKeyName: '中登接口' },
        { dictKey: '4', dictKeyName: '5.0接口' },
        { dictKey: '5', dictKeyName: '公告2.1接口' },
        { dictKey: '6', dictKeyName: '交易2.1接口' },
        { dictKey: '7', dictKeyName: '银行间XML接口' },
    ]; // 接口类型下拉

    ETFTableData: any[] = []; // ETF数据
    ETFTableColumns: any = this.ETFColumnUtil.ETFTableColumns;
    ETFtableLoading: boolean = false;
    ETFPages: any = { currentPage: 1, pageSize: 25, total: 0 };
    ETFTableConfig: TableConfigVO = {
        rowKey: 'no', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    ETFSortFields: any = {}; // etf信息表格排序字段

    stockTableData: any[] = []; // 成分股信息数据
    stockTableColumns: any = this.ETFColumnUtil.stockColumns;
    stockSearchParams: any = {}; // 成分股表格查询参数
    stocktableLoading: boolean = false;
    stockPages: any = { currentPage: 1, pageSize: 25, total: 0 };
    stockTableConfig: TableConfigVO = {
        rowKey: 'no', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    ETFStockSortFields: any = {}; // etf成分股信息表格排序字段
    tableKey: number = 0;

    layoutDialog: boolean = false; // 布局设置loading
    tableColumns: any[] = []; // 布局设置表格所有列
    selectedFieldList: any[] = [];
    showFieldList: any[] = [];
    fixedFieldList: any[] = [
        {
            title: '二级市场代码',
            field: 'stockCode',
            content: '二级市场代码',
            id: 'stockCode',
            minWidth: 160,
            sortable: true,
            filterType: 'search',
            filters: [{}],
            align: 'left',
        },
    ];
    tableName: string = 'ETF_BASIC_INFO'; // 布局设置表名
    // etf基础数据查询表单
    etfQueryForm: any = {
        cashCode: '',
        cashCode2: '',
        creationredemType: [],
        date: null,
        etfCode: '',
        etfType: [],
        importType: [],
        marketCode: [],
        paging: {
            currentPage: 1,
            pageSize: 25,
            total: 0,
        },
        punblish: [],
        purchaseClearSpeed2: [],
        redeemClearSpeed2: [],
        sort: '',
        stockCode: '',
        stockName: '',
        type: [],
    };

    // ETF成分股查询表单
    etfStockQueryForm: any = {
        cashType: [],
        etfStockCode: '',
        execType: '',
        marketCode: [],
        paging: {
            currentPage: 1,
            pageSize: 25,
            total: 0,
        },
        // redeemBalance: 0,
        sort: '',
        stockCode: '',
        stockName: '',
    };

    mounted() {
        let tableColumns = [].concat(this.ETFColumnUtil.ETFTableColumns);
        tableColumns.map(item => {
            item.content = item.title;
            item.id = item.field;
        });
        this.tableColumns = tableColumns;
        // 上表格排序字段
        this.ETFSortFields = this.ETFColumnUtil.etfBasicSortFields;
        // 下表格排序字段
        this.ETFStockSortFields = this.ETFColumnUtil.etfStockSortFields;
        this.queryLayout();
        this.getStockCodeList('');
    }

    @Watch('renderCount')
    onWatchRenderCount() {
        this.queryETFList();
    }

    queryData(args: any) {
        if (args && args.type == 'sort') {
            let field = this.handleSortField(args['sortField'], args['order'], this.ETFSortFields);
            this.etfQueryForm.sort = field;
        }
        this.queryETFList();
    }

    /**
     * 查询二级市场代码下拉数据
     * @param value 搜索值
     * @param stockCodeUrl 证券代码请求路径
     */
    getStockCodeList(value: string) {
        getEtfList(value)
            .then(res => {
                this.stockCodeSelectData = res;
            })
            .catch(() => {
                this.stockCodeSelectData = [];
            });
    }

    /**
     * 查询ETF数据
     */
    queryETFList() {
        this.ETFtableLoading = true;
        getEtfBasicInfoList(this.etfQueryForm)
            .then(res => {
                this.ETFTableData = res.list;
                // this.ETFPages.total = res.total;
                this.etfQueryForm.paging.total = res.total;
                if (res.total) {
                    (this.$refs['ETFTable'] as any).$refs['xTable'].setCurrentRow(res.list[0]);
                    // this.handleETFRowClick(res.list[0]);
                    const row = res.list[0];
                    this.etfStockQueryForm.execType = row.execType;
                    this.etfStockQueryForm.etfStockCode = row.stockCode;
                    this.queryConstituentStock();
                }
                this.ETFtableLoading = false;
            })
            .catch(() => {
                this.ETFtableLoading = false;
            });
    }

    /**
     * 获取排序字段传参
     */
    handleSortField(name: string, order: string, allFields: any): string {
        let value = '';
        let field = '';
        for (const key in allFields) {
            if (name === key) {
                field = allFields[key];
            }
        }
        value = field + ' ' + order;
        return value;
    }

    /**
     * ETF表格行单击事件
     */
    handleETFRowClick(args: any) {
        console.log(args.row, 'handleETFRowClick');
        this.etfStockQueryForm.execType = args.row.execType;
        this.etfStockQueryForm.etfStockCode = args.row.stockCode;
        this.queryConstituentStock();
    }

    //
    queryStockData(args) {
        if (args && args.type == 'sort') {
            let field = this.handleSortField(args['sortField'], args['order'], this.ETFStockSortFields);
            this.etfStockQueryForm.sort = field;
        }
        this.queryConstituentStock();
    }

    /**
     * 查询ETF数据对应的成分股信息
     */
    queryConstituentStock() {
        this.stocktableLoading = true;
        getEtfStockListInfo(this.etfStockQueryForm)
            .then(res => {
                this.stockTableData = res.list;
                this.etfStockQueryForm.paging.total = res.total;
                this.stocktableLoading = false;
            })
            .catch(() => {
                this.stocktableLoading = false;
            });
    }

    // 布局设置提交回调
    async onSubmit(data) {
        await this.queryLayout();
    }

    /**
     * 查询页面布局信息
     */
    async queryLayout() {
        const resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/' + this.tableName)
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        if (resList) {
            this.selectedFieldList = JSON.parse(resList);
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
        } else {
            this.showFieldList = this.tableColumns;
            this.selectedFieldList = this.tableColumns;
        }
        // 表格列的render函数会丢失，需要重新赋值
        let columns = [];
        this.showFieldList.forEach(ele => {
            let index = this.tableColumns.findIndex(item => ele.id == item.id);
            if (index !== -1) {
                columns.push(this.tableColumns[index]);
            }
        });
        this.showFieldList = columns;
        this.tableKey++;
    }
}
</script>
<style lang="scss" scoped>
.pcf-content {
    height: 100%;
    padding: 10px 10px 0px 10px;
    display: flex;
    flex-direction: column;
    .content {
        border: 1px solid #d7d7d7;
        margin-bottom: 10px;
    }
    .search-content {
        padding: 10px;
        width: 100%;
        .el-form {
            display: flex;
            justify-content: space-between;
            .el-select {
                min-width: 8vw;
                width: 100px;
                max-width: 10vw;
            }
            /deep/ .el-form-item {
                margin-bottom: 0px;
                margin-right: 9px;
                .el-form-item__label {
                    font-size: 13px;
                    color: black !important;
                    padding: 0;
                }
                .el-form-item__content {
                    display: flex;
                }
            }
        }
        .operate {
            margin-top: 5px;
        }
    }
    .pcf-table-content {
        height: 40%;
    }
    .stock-table-content {
        height: calc(60% - 90px);
    }
    /deep/ .el-select__tags {
        flex-wrap: nowrap;
    }

    /deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light {
        display: flex;
        align-items: center;
        width: 74%;
        max-width: fit-content;
        padding: 0px;
        margin: 2px 0 2px 2px;
        .el-select__tags-text {
            display: inline-block;
            // max-width: 40px;
            font-size: 12px;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }
    /deep/ .el-select {
        .el-tag__close.el-icon-close {
            right: 1px;
        }
    }
}
// vxe筛选面板高度调整
/deep/.vxe-table--filter-wrapper {
    .vxe-table--filter-body {
        height: 40%;
        max-height: 120px;
        padding-bottom: 0;
    }
    .vxe-table--filter-footer {
        padding: 0.2em;
    }
}
</style>
